﻿using HandyControl.Tools.Extension;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseUi
{
    /// <summary>
    /// 警告信息数据库
    /// </summary>
    public static class WarnInfoDb
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public static bool IsEnabled = false;

        public static SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
        {
            ConnectionString = $"Data Source={Path.Combine(LocalFile.DataDir, "WarnInfo.db3")};Version=3;journal_mode=WAL;",//并发写加入：journal_mode=WAL;
            DbType = DbType.Sqlite,//[Sqlite]安装[System.Data.SQLite.Core];
            IsAutoCloseConnection = true
        }, db =>
        {
            db.Aop.OnError = ex =>
            {
                Logs.Write($@"{nameof(WarnInfoDb)}{Environment.NewLine}SQL:{ex?.Sql}{Environment.NewLine}Parametres:{JsonConvert.SerializeObject(ex?.Parametres)}{Environment.NewLine}InnerException:{ex?.InnerException?.ToString()}{Environment.NewLine}Exception:{ex?.ToString()}{Environment.NewLine}", LogsType.DbErr);
            };
        });

        /// <summary>
        /// 初始化数据
        /// </summary>
        public static void Ini()
        {
            //不存在创建数据库，存在不会创建
            db.DbMaintenance.CreateDatabase();
            //创建表根据实体类
            db.CodeFirst.InitTables(typeof(WarnInfoItemDb));
            IsEnabled = true;
        }

        /// <summary>
        /// 清除数据
        /// </summary>
        /// <param name="time">保留时间</param>
        /// <returns>清理的数量</returns>
        public static int Clear(TimeSpan time)
        {
            try
            {
                if (!IsEnabled)
                    return 0;

                var dt = DateTime.Now.Date.AddDays(1) - time;
                return WarnInfoDb.db.Deleteable<WarnInfoItemDb>().Where(o => o.TimeGo < dt).ExecuteCommand();
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }

    /// <summary>
    /// 警告信息
    /// </summary>
    [SugarTable("WarnInfoItem")]
    [SugarIndex("index_TimeGo", nameof(WarnInfoItemDb.TimeGo), OrderByType.Desc)]
    public class WarnInfoItemDb
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = false)]
        public string Id { get; set; }
        /// <summary>
        /// 来源
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string Source { get; set; }
        /// <summary>
        /// 文本信息
        /// </summary>
        [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString, IsNullable = true)]
        public string Text { get; set; }
        /// <summary>
        /// 级别（提示、警告、错误、致命）
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string Level { get; set; }
        /// <summary>
        /// 解决方案
        /// </summary>
        [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString, IsNullable = true)]
        public string Solution { get; set; }
        /// <summary>
        /// 警告类型
        /// </summary>
        public string WarnType { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime TimeGo { get; set; }
        /// <summary>
        /// 结束时间
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public DateTime? TimeTo { get; set; }
        /// <summary>
        /// 持续时间
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public string DuraTime { get => TimeTo.HasValue ? $"{((int)(TimeTo.Value - TimeGo).TotalHours).ToString().PadLeft(2, '0')}:{(TimeTo.Value - TimeGo).Minutes.ToString().PadLeft(2, '0')}:{(TimeTo.Value - TimeGo).Seconds.ToString().PadLeft(2, '0')}" : ""; }

        public static List<WarnInfoItemDb> GetList(IEnumerable<WarnInfoItem> warnInfos)
        {
            return warnInfos.Select(o => new WarnInfoItemDb()
            {
                Id = o.Id,
                Source = o.Source,
                Text = o.Text,
                Level = o.Level,
                Solution = o.Solution,
                WarnType = o.WarnType == WarnInfoType.AlwayWarn ? "常驻错误" : "循环错误",
                TimeGo = o.TimeGo,
                TimeTo = o.TimeTo,
            }).ToList();
        }
    }
}
